package com.yaoyanshe.trialfield.common.utils;

import android.Manifest;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.RequiresPermission;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import io.reactivex.annotations.NonNull;

/**
 * Date: 2018/03/14 10：30
 *
 * @author tck
 */
public class SystemUtils {

    private SystemUtils() {
    }

    /**
     * 返回当前程序版本名
     */
    public static PackageInfo getAppPackageInfo(Context context) {
        PackageInfo pi = null;
        try {

            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(), 0);

        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return pi;
    }

    /**
     * 获取设备ID
     *
     * @param context
     * @return
     */
    public static String getUniqueId(Context context) {
        String androidID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        String id = androidID + Build.SERIAL;
        try {
            return toMD5(id);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return id;
        }
    }

    /**
     * MD5
     *
     * @param text
     * @return
     * @throws NoSuchAlgorithmException
     */
    private static String toMD5(String text) throws NoSuchAlgorithmException {
        //获取摘要器 MessageDigest
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        //通过摘要器对字符串的二进制字节数组进行hash计算
        byte[] digest = messageDigest.digest(text.getBytes());

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < digest.length; i++) {
            //循环每个字符 将计算结果转化为正整数;
            int digestInt = digest[i] & 0xff;
            //将10进制转化为较短的16进制
            String hexString = Integer.toHexString(digestInt);
            //转化结果如果是个位数会省略0,因此判断并补0
            if (hexString.length() < 2) {
                sb.append(0);
            }
            //将循环结果添加到缓冲区
            sb.append(hexString);
        }
        //返回整个结果
        return sb.toString();
    }

    /**
     * 拨打电话（跳转到拨号界面，用户手动点击拨打）
     *
     * @param context  上下文
     * @param phoneNum 电话号码
     */
    public static void callPhone(@NonNull Context context, String phoneNum) {

        if (TextUtils.isEmpty(phoneNum)) {
            ToastUtils.showToast(context, "手机号为空");
            return;
        }

        try {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            Uri data = Uri.parse("tel:" + phoneNum);
            intent.setData(data);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtils.showToast(context, "找不到相关打开程序");
        }
    }

    /**
     * 拨打电话（跳转到拨号界面，用户手动点击拨打）
     *
     * @param context  上下文
     * @param phoneNum 电话号码
     *                 0 = Intent.ACTION_DIAL不需要权限  1 = Intent.ACTION_CALL需要权限
     */
    @RequiresPermission(Manifest.permission.CALL_PHONE)
    public static void callPhoneWithPermission(@NonNull Context context, String phoneNum) {
        if (TextUtils.isEmpty(phoneNum)) {
            ToastUtils.showToast(context, "手机号为空");
            return;
        }

        try {
            Intent intent = new Intent(Intent.ACTION_CALL);
            Uri data = Uri.parse("tel:" + phoneNum);
            intent.setData(data);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtils.showToast(context, "找不到相关打开程序");
        }
    }

    /**
     * 发送邮件
     *
     * @param context 上下文
     * @param email   邮箱
     */
    public static void sendEmail(@NonNull Context context, String email) {
        if (TextUtils.isEmpty(email)) {
            return;
        }
        try {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            Uri uri = Uri.parse("mailto:" + email);
            intent.setData(uri);
            context.startActivity(Intent.createChooser(intent, "请选择"));
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
            ToastUtils.showToast(context, "找不到相关打开程序");
        }
    }

    public static void jumpBrowser(Context context, String url) {

        if (TextUtils.isEmpty(url)) {
            ToastUtils.showToast(context, "网址为空");
            return;
        }
        try {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            Uri uri = Uri.parse(url);
            intent.setData(uri);
            context.startActivity(Intent.createChooser(intent, "请选择浏览器"));
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
            ToastUtils.showToast(context, "找不到相关打开程序");
        }
    }

    /**
     * 判断进程是否存活
     *
     * @param context
     * @return
     */
    public static boolean isAppAlive(@NonNull Context context) {
        ActivityManager am = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = context.getPackageName();
        //获取本App的唯一标识
        int myPid = android.os.Process.myPid();
        //利用一个增强for循环取出手机里的所有进程
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            //通过比较进程的唯一标识和包名判断进程里是否存在该App
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取app的渠道
     *
     * @param context
     * @param metaKey AndroidManifest 配置的meta-data标签的name
     * @return 返回对应的渠道，默认dia
     */
    public static String getAppChannel(Context context, String metaKey) {

        if (context == null || TextUtils.isEmpty(metaKey)) {
            return "xy";
        }

        try {
            ApplicationInfo applicationInfo = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            if (applicationInfo.metaData == null) {
                return "xy";
            }
            return applicationInfo.metaData.getString(metaKey);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return "xy";
    }

    /**
     * 跳转设置页面
     */
    public static void goToSetting(@NonNull Context context) {
        Intent localIntent = new Intent(Settings.ACTION_SETTINGS);
        context.startActivity(localIntent);
    }

    public static boolean isHttpUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            return false;
        }
        try {
            Uri parse = Uri.parse(url);
            String scheme = parse.getScheme();
            if (scheme == null || scheme.length() == 0) {
                return false;
            }
            return scheme.startsWith("http");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String getConfigJsonFromAssets(@NonNull Context context, @NonNull String name) {
        StringBuilder stringBuilder = new StringBuilder();
        InputStream openInputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        try {
            AssetManager assets = context.getAssets();
            openInputStream = assets.open(name);
            inputStreamReader = new InputStreamReader(openInputStream);
            bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (Exception e) {
            YLogger.d("getConfigJsonFromAssets error:" + e.getMessage());
        } finally {
            try {
                if (openInputStream != null) {
                    openInputStream.close();
                }
            } catch (Exception e) {
                YLogger.d("getConfigJsonFromAssets openInputStream close error:" + e.getMessage());
            }
        }
        if (inputStreamReader != null) {
            try {
                inputStreamReader.close();
            } catch (Exception e) {
                YLogger.d("getConfigJsonFromAssets inputStreamReader close error:" + e.getMessage());
            }
        }
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (Exception e) {
                YLogger.d("getConfigJsonFromAssets bufferedReader close error:" + e.getMessage());
            }
        }
        return stringBuilder.toString();
    }
}
